package service

import (
	"context"
	"errors"
	"go-admin/server/internal/domain"
	"go-admin/server/internal/repository"
	"golang.org/x/crypto/bcrypt"
)

var (
	ErrAdminDuplicate        = repository.ErrAdminDuplicate
	ErrInvalidUserOrPassword = errors.New("账号或者密码不对")
)

type AdminServer interface {
	CreateAdmin(ctx context.Context, admin domain.Admin) error
	UpdateAdmin(ctx context.Context, AdminId int64, admin domain.Admin) error
	UpdateStatus(ctx context.Context, AdminId int64, Status int32) error
	GetAdminLst(ctx context.Context, data domain.PageInfo) ([]domain.Admin, int64, error)

	Login(ctx context.Context, account, password string) (domain.Admin, error)
	UpdatePassword(ctx context.Context, adminId int64, password string) error
}

type adminServer struct {
	repo repository.AdminRepository
}

func NewAdminServer(repo repository.AdminRepository) AdminServer {
	return &adminServer{
		repo: repo,
	}
}

func (a *adminServer) CreateAdmin(ctx context.Context, admin domain.Admin) error {
	return a.repo.CreateAdmin(ctx, admin)
}

func (a *adminServer) UpdateAdmin(ctx context.Context, AdminId int64, admin domain.Admin) error {
	return a.repo.UpdateAdmin(ctx, AdminId, admin)
}

func (a *adminServer) UpdateStatus(ctx context.Context, AdminId int64, Status int32) error {
	return a.repo.UpdateStatus(ctx, AdminId, Status)
}
func (a *adminServer) UpdatePassword(ctx context.Context, adminId int64, password string) error {
	return a.repo.UpdatePassword(ctx, adminId, password)
}

func (a *adminServer) GetAdminLst(ctx context.Context, data domain.PageInfo) ([]domain.Admin, int64, error) {
	lsit, total, err := a.repo.GetAdminLst(ctx, data)
	return lsit, total, err
}

func (a *adminServer) Login(ctx context.Context, account, password string) (domain.Admin, error) {
	u, err := a.repo.FindByEmailOrLoginName(ctx, account)
	if errors.Is(err, repository.ErrAdminNotFound) {
		return domain.Admin{}, ErrInvalidUserOrPassword
	}
	if err != nil {
		return domain.Admin{}, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err != nil {
		return domain.Admin{}, ErrInvalidUserOrPassword
	}
	return u, nil
}
